// PrivateMessageController.java
package com.training.bt.controller;

import com.training.bt.entity.PrivateMessage;
import com.training.bt.security.util.SecurityUtils;
import com.training.bt.service.IPrivateMessageService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/messages")
@RequiredArgsConstructor
public class PrivateMessageController {

    private final IPrivateMessageService messageService;

    // 发送消息（自动验证Token）
    @PostMapping
    public ResponseEntity<PrivateMessage> sendMessage(@RequestBody PrivateMessage message) {
        Long senderId = SecurityUtils.getCurrentUser().getId();

        message.setSenderId(senderId);

        PrivateMessage savedMessage = messageService.sendMessage(message);
        return new ResponseEntity<>(savedMessage, HttpStatus.CREATED);
    }

    // 获取两个用户之间的对话记录
    @GetMapping("/conversation/{otherUserId}")
    public ResponseEntity<List<PrivateMessage>> getConversation(@PathVariable Long otherUserId) {
        Long currentUserId = SecurityUtils.getCurrentUser().getId();
        List<PrivateMessage> messages = messageService.getConversation(currentUserId, otherUserId);
        return new ResponseEntity<>(messages, HttpStatus.OK);
    }

    // 获取用户的未读消息数量
    @GetMapping("/unread")
    public ResponseEntity<Long> getUnreadMessageCount(HttpServletRequest request) {
        Long userId = SecurityUtils.getCurrentUser().getId();
        Long count = messageService.getUnreadMessageCount(userId);
        return new ResponseEntity<>(count, HttpStatus.OK);
    }

    // 标记消息为已读
    @PostMapping("/markAsRead/{senderId}")
    public ResponseEntity<Map<String, String>> markMessagesAsRead(@PathVariable Long senderId) {
        Long currentUserId = SecurityUtils.getCurrentUser().getId();

        messageService.markMessagesAsRead(currentUserId, senderId);

        Map<String, String> response = new HashMap<>();
        response.put("status", "success");
        response.put("message", "Messages marked as read");
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
}